package com.example.demo.aspect;

import com.example.demo.entity.Log;
import com.example.demo.service.LogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
public class MyAspect {
    @Autowired
    LogService logService;
    @Pointcut("execution(* com.example.demo.controller.*.*(..))")
    public void pointcut(){}
    @After("pointcut()")
        public void after(JoinPoint joinPoint){
        System.out.println("这是后置通知！");
        HttpServletRequest request = (HttpServletRequest) RequestContextHolder.currentRequestAttributes()
                .resolveReference(RequestAttributes.REFERENCE_REQUEST);
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null){
            ipAddress = request.getRemoteAddr();
        }
        Log log = new Log(ipAddress,joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName(),"");
        logService.addLog(log);
    }
}

